﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Web;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Model;
using System.Net;
using System.Configuration;
namespace DAL
{
    public class Commons
    {
        //参数设置 <-----参数需要重新设置----->
        //http的域名
        private static String HOST = "http://sdk.open.api.igexin.com/apiex.htm";

        //https的域名
        //private static String HOST = "https://api.getui.com/apiex.htm";

        //定义常量, appId、appKey、masterSecret 采用本文档 "第二步 获取访问凭证 "中获得的应用配置
        private static String APPID = "hcFHiDvIWP6Sk2QYTSmW";
        private static String APPKEY = "xgcOleV3dN64IKtgJMi1W4";
        private static String MASTERSECRET = "0P8UlSjUXI7u5yppsEZW37";
        private static String CLIENTID = "5cb30ca5fa54fb9145f9f70a86eedc77";

        private static String DeviceToken = "A6198F6ED3B5CA8E8B22E6A716C35752DBD083F6E1DEEB6145C96E89EE49259B";  //填写IOS系统的DeviceToken
        public static Dictionary<int, string> Power = new Dictionary<int, string>(); //用户权限
        public static Dictionary<int, string> Job = new Dictionary<int, string>(); //客户行业
        public static Dictionary<int, string> StaffNum = new Dictionary<int, string>(); //客户公司员工人数
        public static Dictionary<int, string> PayType = new Dictionary<int, string>(); //支付方式
        public static Dictionary<int, string> OrderState = new Dictionary<int, string>(); //订单状态
        public static Dictionary<int, string> Logistics = new Dictionary<int, string>(); //物流公司

        public static Dictionary<int, string> DailyState = new Dictionary<int, string>(); //日志状态
        public static Dictionary<int, string> DailyScore = new Dictionary<int, string>(); //日志评分
        public static Dictionary<int, string> TaskState = new Dictionary<int, string>(); //任务状态
        public static Dictionary<int, string> TaskReply = new Dictionary<int, string>(); //任务回复
        public static Dictionary<int, string> TableName = new Dictionary<int, string>(); //表名
        public static Dictionary<int, string> TableText = new Dictionary<int, string>(); //表名
        public static Dictionary<int, string> ExamineType = new Dictionary<int, string>(); //审批类型
        public static Dictionary<int, string> ExamineState = new Dictionary<int, string>(); //审批状态
        public static Dictionary<int, string> ExamineNum = new Dictionary<int, string>(); //审批流程
        public static Dictionary<int, string> ExamineReplyState = new Dictionary<int, string>(); //审批回复状态
        public static Dictionary<int, string> SignState = new Dictionary<int, string>(); //签到状态
        public static string domain = "http://www.qiyedaishu.com";

        public static string GetSuccess(string msg, object data)
        { 
            dynamic dy = new ExpandoObject();
            dy.state = true;
            dy.msg = msg;
            dy.data = data;
            return SerializeHelper.ToJsonByDynamic(dy);
        }
        public static string GetFaild(string msg)
        {
            dynamic dy = new ExpandoObject();
            dy.state = false;
            dy.msg = msg;
            return SerializeHelper.ToJsonByDynamic(dy);
        }
        /// <summary>
        /// URL字符编码
        /// </summary>
        public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpContext.Current.Server.UrlEncode(str);
        }

        /// <summary>
        /// URL字符解码
        /// </summary>
        public static string UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }

        //删除文件夹下的图片
        /// <summary>
        /// 
        /// </summary>
        /// <param name="imgs">数据库中存储的图片路径</param>
        public static void DeleteImg(List<string> imgs)
        {
            try
            {
                foreach (string img in imgs)
                {
                    string path = img.Substring(0, img.LastIndexOf('/'));
                    Directory.Delete(HttpContext.Current.Server.MapPath(path), true);
                }
            }
            catch (Exception ex) { }
        }
        //删除文件夹下的图片
        /// <summary>
        /// 
        /// </summary>
        /// <param name="imgs">数据库中存储的图片路径</param>
        public static void DeleteOnlyImg(List<string> imgs)
        {
            try
            {
                foreach (string img in imgs)
                {
                    File.Delete(HttpContext.Current.Server.MapPath(img));
                }
            }
            catch (Exception ex) { }
        }
        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <param name="head">前缀，比如:PO</param>
        /// <param name="num">单号</param>
        /// <returns></returns>
        public static string ToNum(string head, string num)
        {
            var newnum = "";
            var date = DateTime.Now.ToString("yyyyMMdd");
            if (num == "" || num == null)
            {
                newnum = head + date + "0001";
            }
            else
            {
                if (num.Length == 14)
                {
                    int maxnum = int.Parse(num.Substring(10, 4)) + 1;
                    if (maxnum.ToString().Length == 1)
                    {
                        newnum = newnum = head + date + "000" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 2)
                    {
                        newnum = newnum = head + date + "00" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 3)
                    {
                        newnum = newnum = head + date + "0" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 4)
                    {
                        newnum = newnum = head + date + maxnum;
                    }
                    else { }
                }
            }
            return newnum;
        }

        public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

            if (!Directory.Exists(toDir))
            {
                Directory.CreateDirectory(toDir);
            }

            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }

        public static void MoveDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

            CopyDir(fromDir, toDir);
            Directory.Delete(fromDir, true);
        }

        public static void MoveFile(int comid, int userid, string img, bool isdelete)
        {
            try
            {
                string new_img = "";
                string old_path = img.Substring(0, img.LastIndexOf('/'));
                new_img = img.Replace("temp/", "");
                string new_path = new_img.Substring(0, new_img.LastIndexOf('/') + 1);
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(new_path)))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(new_path));
                    DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(old_path));
                    foreach (FileInfo fi in di.GetFiles())//可以用 di.GetFiles("*.jpg") 只移动jpg文件
                    {
                        fi.MoveTo(HttpContext.Current.Server.MapPath(new_path) + fi.Name);
                    }
                    if (isdelete)
                    {
                        Directory.Delete(HttpContext.Current.Server.MapPath("/upload/temp/" + comid + "/" + userid + "/"), true);
                    }
                }
            }
            catch (Exception ex)
            { 
            }
        }
        public static void MoveFile(string img, bool isdelete)
        {
            try
            {
                if (isdelete)
                {
                    string new_annex = "";
                    string old_path = img.Substring(0, img.LastIndexOf('/'));
                    new_annex = img.Replace("temp/", "");
                    string new_path = new_annex.Substring(0, new_annex.LastIndexOf('/') + 1);
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(new_path)))
                    {
                        Commons.MoveDir(HttpContext.Current.Server.MapPath(old_path), HttpContext.Current.Server.MapPath(new_path));
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        public static string getMonthDay(DateTime date)
        {
            string year_day = "";
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }
            
            return year_day;
        }
        public static string getMonthDayHourMinute(DateTime date)
        {
            string year_day = "";
            string minite = date.Minute.ToString();
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }
            if (minite.Length < 2)
            {
                minite = "0" + minite;
            }
            return year_day + date.Hour + ":" + minite;
        }
        public static string getMonthDayHourMinute2(DateTime date)
        {
            string year_day = "";
            string minite = date.Minute.ToString();
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.ToString("MM-dd");
                }
            }
            else
            {
                year_day = date.ToString("MM-dd");
            }
            return date.ToString("HH:mm") + " " + year_day;
        }
        public static string GetImg(string path, int size)
        {
            string[] files = path.Split('.');
            string ext = "." + files[files.Length - 1];
            return Commons.domain + path.Replace(ext,"") + "_" + size + ext;
        }
        public static string GetImg2(string path, int size)
        {
            string[] files = path.Split('.');
            string ext = "." + files[files.Length - 1];
            return path.Replace(ext, "") + "_" + size + ext;
        }
        //解决头像路径参数里有小数点
        public static string GetHead(string path, int size)
        {
            int index = path.IndexOf('.');
            return Commons.domain + path.Substring(0,index) + "_" + size + path.Substring(index,path.Length-index);
        }
        //字符串前后加逗号
        public static string TranDou(object str)
        {
            str = str.ToString().Trim(',');
            return str.ToString() == "" ? "" : "," + str + ",";
        }

        public static string GetWebClientIP()
        {

            string userIP = "未获取用户IP";

            try
            {
                if (System.Web.HttpContext.Current == null
            || System.Web.HttpContext.Current.Request == null
            || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    return "";

                string CustomerIP = "";

                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (!String.IsNullOrEmpty(CustomerIP))
                    return CustomerIP;

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                return CustomerIP;
            }
            catch { }

            return userIP;

        }

        
        public static string FilterHTML2(string html)
        {
            if (html == null)
            {
                html = "";
            }
            html = html.ToLower();
            System.Text.RegularExpressions.Regex regex1 =
                  new System.Text.RegularExpressions.Regex(@"<script[sS]+</script *>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 =
                  new System.Text.RegularExpressions.Regex(@" href *= *[sS]*script *:",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 =
                  new System.Text.RegularExpressions.Regex(@" no[sS]*=",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 =
                  new System.Text.RegularExpressions.Regex(@"<iframe[sS]+</iframe *>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 =
                  new System.Text.RegularExpressions.Regex(@"<frameset[sS]+</frameset *>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex6 =
                  new System.Text.RegularExpressions.Regex(@"<img[^>]+>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex7 =
                  new System.Text.RegularExpressions.Regex(@"</p>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex8 =
                  new System.Text.RegularExpressions.Regex(@"<p>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex9 =
                  new System.Text.RegularExpressions.Regex(@"<[^>]*>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记 
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 
            html = regex4.Replace(html, ""); //过滤iframe 
            html = regex5.Replace(html, ""); //过滤frameset 
            html = regex6.Replace(html, ""); //过滤frameset 
            html = regex7.Replace(html, ""); //过滤frameset 
            html = regex8.Replace(html, ""); //过滤frameset 
            html = regex9.Replace(html, "");
            //html = html.Replace(" ", "");
            html = html.Replace("</strong>", "");
            html = html.Replace("<strong>", "");
            html = Regex.Replace(html, "[\f\r\t\v]", "");  //过滤回车换行制表符

            return html;
        }
        public static string FilterHTML(string str)
        {
            str = Regex.Replace(str, @"<[\s\S]*?>", "");
            return str.Replace("&nbsp;", "");
        }
        public static string SubString(string str, int len)
        {
            str = FilterHTML(DataConvert.ToString(str));
            if (str.Length > len)
            {
                return str.Substring(0, len);
            }
            else
            {
                return str;
            }
        }
        public static string GetIP()
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

        public static string GetWeek()
        {
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
        }
        /// <summary>
        /// 计算两个日期的时间间隔,返回的是时间间隔的日期差的绝对值.
        /// </summary>
        /// <param name="DateTime1">第一个日期和时间</param>
        /// <param name="DateTime2">第二个日期和时间</param>
        /// <returns></returns>
        public static int DateDiff(DateTime DateTime1, DateTime DateTime2, string Flag)
        {
            double dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                if (Flag == "D")
                {
                    dateDiff = ts.TotalDays;
                }else if (Flag == "H")
                {
                    dateDiff = ts.TotalHours;
                }
                else if (Flag == "M")
                {
                    dateDiff = ts.TotalMinutes;
                }
                else if (Flag == "S")
                {
                    dateDiff = ts.TotalSeconds;
                }

            }
            catch
            {
            }
            return (int)dateDiff;
        }

        /// <summary>
        /// 获取字符中指定标签的值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="title">标签</param>
        /// <returns>值</returns>
        public static string GetTitleContent100(string str, string title)
        {
            string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</{1}>", title, title); //获取<title>之间内容
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["Text"].Value;
            return result;
        }

        /// <summary>  
        /// 获取字符中指定标签的值  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <param name="title">标签</param>  
        /// <param name="attrib">属性名</param>  
        /// <returns>属性</returns>  
        public static string GetAttrContent100(string str, string title, string attrib)
        {
            string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<url>[^'\"\"\\s>]+)\\1[^>]*>", title, attrib); //获取<title>之间内容  
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["url"].Value;
            return result;
        }

        /// <summary>
        /// 获取字符中指定标签的值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="title">标签</param>
        /// <returns>值</returns>
        public static string GetTitleContent(string str, string title)
        {
            string tmpStr = string.Format("<{0}[^>]*?>(?<Text>[^<]*)</{1}>", title, title); //获取<title>之间内容
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["Text"].Value;
            return result;
        }

        /// <summary>  
        /// 获取字符中指定标签的值  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <param name="title">标签</param>  
        /// <param name="attrib">属性名</param>  
        /// <returns>属性</returns>  
        public static string GetAttrContent(string str, string title, string attrib)
        {
            string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<url>[^'\"\"\\s>]+)\\1[^>]*>", title, attrib); //获取<title>之间内容  
            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);
            string result = TitleMatch.Groups["url"].Value;
            return result;
        }

        public static double CalcDistance(double fromX, double fromY, double toX, double toY)
        {
            double rad = 6371; //Earth radius in Km

            //Convert to radians

            double p1X = fromX / 180 * Math.PI;

            double p1Y = fromY / 180 * Math.PI;

            double p2X = toX / 180 * Math.PI;

            double p2Y = toY / 180 * Math.PI;

            return Math.Acos(Math.Sin(p1Y) * Math.Sin(p2Y) +

                Math.Cos(p1Y) * Math.Cos(p2Y) * Math.Cos(p2X - p1X)) * rad * 1000;
        }

        //获取config文件value
        public static string GetConfig(string key)
        {
            if (!string.IsNullOrEmpty(key) &&
                ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                return ConfigurationManager.AppSettings[key].ToString();
            }
            return string.Empty;
        }

        public static string TranText(string str)
        {
            return str.Replace("\r", "<br>").Replace("\n", "<br>").Replace("\r\n", "<br>");
        }
        public static void Log(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true);//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        public static bool CheckSign()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string action = JobRequest.GetRequestString("act");
                string sign = JobRequest.GetRequestString("sign");
                sb.AppendFormat("account={0}&act={1}&key={2}", "QiYeDaiShu_CLIENT", action, "265B6B86CA6E43A552G363078D5ADCFE");
                string signstr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToLower();
                return sign == signstr;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
